package com.chaos.framework.model.valid;



import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class EnumValidator implements ConstraintValidator<EnumCodeValid, Integer> {

    private EnumCodeValid annotation;

    @Override
    public void initialize(EnumCodeValid constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        Class<? extends EnumCode> enumClass = annotation.enumClass();

        if (!enumClass.isEnum()) {
            throw new IllegalArgumentException(enumClass.getSimpleName() + "不是枚举类型");
        }

        try {
            Method getCodeMethod = enumClass.getMethod("getCode");
            for (EnumCode enumConstant : enumClass.getEnumConstants()) {
                Object codeValue = getCodeMethod.invoke(enumConstant);
                if (value.equals(codeValue)) {
                    return true;
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new IllegalArgumentException("从枚举[" + enumClass.getSimpleName() + "]获取值失败", e);
        }
        return false;
    }
}
